package com.karrim.server.io.sql;

import com.karrim.server.io.sql.def.SQLLocator;
import com.karrim.server.io.sql.def.SQLStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author andrea.cantafio
 */
public abstract class AbstractSQLStream implements SQLStream {

    public AbstractSQLStream(String connectionString, String driver) throws ClassNotFoundException {
        this.connectionString = "".equals(connectionString) ? null : connectionString;
        this.driver = driver;
        Class.forName(driver);
    }

    public Connection connect(final String target) throws SQLException {
        return open(new SQLLocator() {
            @Override
            public String get() {
                return target;
            }
        });
    }

    @Override
    public Connection open(SQLLocator locable) {
        try {
            return tryOpen(locable);
        } catch (SQLException ex) {
            Logger.getLogger(AbstractSQLStream.class.getName()).log(Level.SEVERE, null, ex);
            return null;
        }
    }

    @Override
    public Connection tryOpen(SQLLocator locable) throws SQLException {
        return (connection = DriverManager.getConnection(locable.get()));
    }

    @Override
    public Connection get() {
        if (connection == null && connectionString != null) {
            try {
                return connect(connectionString);
            } catch (SQLException sqle) {
                return null;
            }
        }
        return connection;
    }
    private Connection connection;
    private String connectionString;
    private String driver;
}
